﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace BuildForm
{
    public partial class Categories : Form
    {
        SqlCommand cmd;
        SqlConnection con;
        public Categories()
        {
            InitializeComponent();
            con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            LoadCategoriesInfo();
            btnUpdate.Enabled = false;
            btnDelete.Enabled = false;
        }

        #region Code
        bool validateInput()
        {
            errorProvider1.Clear();
            bool error = false;
            try
            {
                #region Check Enter
                if (txtCategoryName.Text.Trim().Length == 0)
                {
                    errorProvider1.SetError(txtCategoryName, "Input Category Name!");
                    error = true;
                }
                if (txtDescription.Text.Trim().Length == 0)
                {
                    errorProvider1.SetError(txtDescription, "Input Description!");
                    error = true;
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (error == true)
            {
                return false;
            }
            return true;
        }

        void LoadCategoriesInfo()
        {
            gvCategory.Rows.Clear();
            con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM Production.Categories";
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    gvCategory.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2].ToString());
                }
                dr.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                con.Close();
            }
        }

        void addCategory()
        {
            try
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_Categories_Insert";

                SqlParameter param = new SqlParameter("@categoryname", SqlDbType.NVarChar, 15);
                param.Value = txtCategoryName.Text;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@description", SqlDbType.NVarChar, 200);
                param.Value = txtDescription.Text;
                cmd.Parameters.Add(param);

                cmd.ExecuteNonQuery();
                MessageBox.Show("Add Successfully!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
                LoadCategoriesInfo();
            }
        }

        void updateCategory()
        {
                try
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                    con.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "sp_Categoris_Update";

                    SqlParameter param = new SqlParameter("@categoryid", SqlDbType.Int);
                    param.Value = txtCategoryID.Text;
                    cmd.Parameters.Add(param);

                    param = new SqlParameter("@categoryname", SqlDbType.NVarChar);
                    param.Size = 15;
                    param.Value = txtCategoryName.Text;
                    cmd.Parameters.Add(param);

                    param = new SqlParameter("@description", SqlDbType.NVarChar);
                    param.Size = 200;
                    param.Value = txtDescription.Text;
                    cmd.Parameters.Add(param);

                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Update Successfully!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {

                    con.Close();
                    LoadCategoriesInfo();
                }
            }
        void deleteCategory()
        {
            try
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_Categories_Delete";

                SqlParameter param = new SqlParameter("@categoryid", SqlDbType.Int);
                param.Value = txtCategoryID.Text;
                cmd.Parameters.Add(param);

                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw(ex);
            }
            finally
            {
                con.Close();                
                LoadCategoriesInfo();
            }
        }

        void InitData()
        {
            errorProvider1.Clear();
            btnAdd.Enabled = true;
            btnUpdate.Enabled = false;
            btnDelete.Enabled = false;
            txtCategoryID.Clear();
            txtCategoryName.Clear();
            txtDescription.Clear();
            txtSearch.Clear();
        }
        void SearchCategory()
        {
            try
            {
                gvCategory.Rows.Clear();
                con.Open();
                cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                if (cbSearch.SelectedIndex == 0)
                    cmd.CommandText = string.Format("SELECT * FROM Production.Categories WHERE categoryname LIKE '%{0}%'", txtSearch.Text);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    gvCategory.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2].ToString());
                }

                dr.Close();
            }
            catch (Exception ex)
            {
                throw(ex);
            }
            finally
            {
                con.Close();
            }
        }
        #endregion

        #region Event
        private void btnNew_Click(object sender, EventArgs e)
        {
            InitData();
            LoadCategoriesInfo();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (validateInput() == true)
            {
                addCategory();
            }
            
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (validateInput() ==  true)
            {
                updateCategory();
                 
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Boolean check=true;
            try
            {
                DialogResult rs= MessageBox.Show("Are You Sure !", "Warning", MessageBoxButtons.YesNo);
                if (rs == DialogResult.Yes)
                    deleteCategory();
                else
                    check = false;
            }
            catch 
            {
                check = false;
                MessageBox.Show("Can not Delete!","Error");
            }
            if (check)
            {
                MessageBox.Show("Delete Successfully!");
                InitData();
            }
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            LoadCategoriesInfo();
        }

        private void gvCategory_SelectionChanged(object sender, EventArgs e)
        {
            if (gvCategory.SelectedRows.Count > 0)
            {
                errorProvider1.Clear();
                btnUpdate.Enabled = true;
                btnDelete.Enabled = true;
                btnAdd.Enabled = false;
                DataGridViewRow r = gvCategory.SelectedRows[0];
                txtCategoryID.Text = r.Cells["clCategoryID"].Value.ToString();
                txtCategoryName.Text = r.Cells["clCategoryName"].Value.ToString();
                txtDescription.Text = r.Cells["clDescription"].Value.ToString();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                if (cbSearch.SelectedIndex == -1)
                    MessageBox.Show("Please choose Search by ?","notification");
                else
                SearchCategory();
            }
            catch 
            {
                MessageBox.Show("Search fail","Error");
            }
        }
        #endregion
    }
}
